<?php
require_once(CORE_DIR.'Common.php');
require_once(CORE_DIR.'mappers/TaskTypeMapper.php');

class tasktypeModel extends Model{
	
	function __construct(){
		$this->conn = $this->getConnection();
	}
	
	function addTaskType($tskTypeName, $tskTypeDesc){
		$newOrderId = $this->getNewTaskTypeOrder();
		$query = "insert into tasktype (name, description, order_id)
				  values ('%s', '%s', %d)";
		$query = $this->format($query, array($tskTypeName, $tskTypeDesc, $newOrderId));
		$list = $this->execute($query, new TaskTypeMapper());	
		$tasktype_id =  mysqli_insert_id($this->conn);
		return $tasktype_id;
	}
	
	function updateTaskType($id, $tsktypeName, $tsktypeDesc, $tsktypeOrderList){
		$this->updateTaskListOrder($tsktypeOrderList);
		
		$query = "update tasktype set name='%s', description='%s' where id=%d";
		$query = $this->format($query, array($tsktypeName, $tsktypeDesc, $id));		
		$list = $this->execute($query, new TaskTypeMapper());	
		return mysqli_affected_rows($this->conn);	
	}

	function deleteTaskType($id){
		if($id == 1)
			return 2;
		$query = "delete from tasktype where id=%d";
		$query = $this->format($query, array($id));		
		$list = $this->execute($query, new TaskTypeMapper());	
		return mysqli_affected_rows($this->conn);
	}		
	
	function getTaskTypes(){
		$query = "SELECT * FROM tasktype ORDER BY order_id";		
		return $this->execute($query, new TaskTypeMapper());
	}
	
	function getNewTaskTypeOrder(){		
		$query = "SELECT MAX(order_id)+1 as order_id FROM tasktype";
		$list = $this->execute($query, new TaskTypeMapper());
		return $list[0]->getOrderId();
	}
	
	function updateTaskListOrder($orderList){
		for ($i = 0; $i < count($orderList); $i++){
			$query = "update tasktype set order_id = %d where id = %d";
			$query = $this->format($query, array($i+1, $orderList[$i]));
			$res = $this->execute($query, new TaskTypeMapper());	
		}
	}
}
?>
